package top.yokey.shopai.main.fragment;

import android.view.LayoutInflater;
import android.view.View;

import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;
import com.google.zxing.client.android.MNScanManager;
import com.google.zxing.client.android.model.MNScanConfig;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.util.ArrayList;

import top.yokey.shopai.R;
import top.yokey.shopai.main.adapter.MainSpecialAdapter;
import top.yokey.shopai.main.viewmodel.MainHomeVM;
import top.yokey.shopai.zcom.App;
import top.yokey.shopai.zcom.adapter.ViewPagerAdapter;
import top.yokey.shopai.zcom.arouter.ARoutePath;
import top.yokey.shopai.zcom.base.BaseFragment;
import top.yokey.shopai.zcom.help.DialogHelp;
import top.yokey.shopai.zcom.help.ToastHelp;
import top.yokey.shopai.zcom.other.Constant;
import top.yokey.shopai.zcom.util.ConvertUtil;
import top.yokey.shopai.zcom.view.PullRefreshView;
import top.yokey.shopai.zsdk.ShopAISdk;
import top.yokey.shopai.zsdk.bean.SpecialBean;
import top.yokey.shopai.zsdk.bean.SpecialListBean;
import top.yokey.shopai.zsdk.callback.HtmlCallBack;

public class MainHomeFragment extends BaseFragment {

    private final ArrayList<String> idArrayList = new ArrayList<>();
    private AppCompatEditText searchEditText = null;
    private AppCompatImageView scanImageView = null;
    private AppCompatImageView messageImageView = null;
    private AppCompatTextView messageDotTextView = null;
    private TabLayout mainTabLayout = null;
    private ViewPager mainViewPager = null;
    private PullRefreshView[] mainPullRefreshView = null;
    private MainHomeVM vm = null;
    private ArrayList<SpecialBean>[] arrayList = null;

    @Override
    public View initView() {

        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_main_home, null);
        searchEditText = view.findViewById(R.id.searchEditText);
        scanImageView = view.findViewById(R.id.scanImageView);
        messageImageView = view.findViewById(R.id.messageImageView);
        messageDotTextView = view.findViewById(R.id.messageDotTextView);
        mainTabLayout = view.findViewById(R.id.mainTabLayout);
        mainViewPager = view.findViewById(R.id.mainViewPager);
        return view;

    }

    @Override
    public void initData() {

        vm = getVM(MainHomeVM.class);
        vm.getSpecialList();

    }

    @Override
    public void initEvent() {

        searchEditText.setOnClickListener(view -> App.get().start(ARoutePath.MAIN_SEARCH));

        scanImageView.setOnClickListener(view -> {
            MNScanConfig scanConfig = new MNScanConfig.Builder()
                    .isShowVibrate(false)
                    .isShowBeep(true)
                    .isShowPhotoAlbum(true)
                    .setScanHintText(getString(R.string.qrCodeScan))
                    .setZoomControllerLocation(MNScanConfig.ZoomControllerLocation.Bottom)
                    .isShowZoomController(true)
                    .builder();
            MNScanManager.startScan(requireActivity(), scanConfig, (code, data) -> {
                switch (code) {
                    case MNScanManager.RESULT_SUCCESS:
                        String result = data.getStringExtra(MNScanManager.INTENT_KEY_RESULT_SUCCESS);
                        if (result.contains(Constant.URL)) {
                            if (result.contains("=fx_goods")) {
                                ShopAISdk.get().getLocation(result, new HtmlCallBack() {
                                    @Override
                                    public void onSuccess(String result) {
                                        App.get().startUrl(result);
                                    }

                                    @Override
                                    public void onFailure(String reason) {
                                        ToastHelp.get().show(reason);
                                    }
                                });
                                return;
                            }
                            App.get().startUrl(result);
                            return;
                        }
                        ToastHelp.get().show(data.getStringExtra(MNScanManager.INTENT_KEY_RESULT_SUCCESS));
                        break;
                    case MNScanManager.RESULT_FAIL:
                        ToastHelp.get().show(data.getStringExtra(MNScanManager.INTENT_KEY_RESULT_ERROR));
                        break;
                }
            });
        });

        messageImageView.setOnClickListener(view -> App.get().start(ARoutePath.MEMBER_MESSAGE));

    }

    @Override
    public void initObserve() {

        vm.getSpecialListLiveData().observe(this, list -> {
            //顶部导航
            idArrayList.clear();
            ArrayList<View> viewList = new ArrayList<>();
            ArrayList<String> titleList = new ArrayList<>();
            idArrayList.add("0");
            titleList.add(getString(R.string.recommend));
            viewList.add(getLayoutInflater().inflate(R.layout.include_pull_refresh_view, null));
            SpecialListBean specialListBean;
            for (int i = 0; i < list.size(); i++) {
                specialListBean = list.get(i);
                idArrayList.add(specialListBean.getSpecialId());
                titleList.add(specialListBean.getSpecialDesc());
                viewList.add(getLayoutInflater().inflate(R.layout.include_pull_refresh_view, null));
            }
            App.get().setTabLayout(mainTabLayout, mainViewPager, new ViewPagerAdapter(viewList, titleList));
            //主要内容
            //noinspection unchecked
            arrayList = new ArrayList[idArrayList.size()];
            MainSpecialAdapter[] adapter = new MainSpecialAdapter[idArrayList.size()];
            mainPullRefreshView = new PullRefreshView[idArrayList.size()];
            for (int i = 0; i < mainPullRefreshView.length; i++) {
                final int pos = i;
                arrayList[i] = new ArrayList<>();
                adapter[i] = new MainSpecialAdapter(arrayList[i]);
                mainPullRefreshView[i] = viewList.get(i).findViewById(R.id.mainPullRefreshView);
                mainPullRefreshView[i].setCanLoadMore(false);
                mainPullRefreshView[i].setAdapter(adapter[i]);
                mainPullRefreshView[i].setOnClickListener(view -> {
                    if (mainPullRefreshView[pos].isError() || arrayList[pos].size() == 0) {
                        if (pos == 0) {
                            mainPullRefreshView[0].setLoad();
                            vm.getIndex();
                        } else {
                            mainPullRefreshView[pos].setLoad();
                            vm.getSpecial(pos, idArrayList.get(pos));
                        }
                    }
                });
                mainPullRefreshView[i].setOnRefreshListener(new PullRefreshView.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
                        if (pos == 0) {
                            mainPullRefreshView[0].setLoad();
                            vm.getIndex();
                        } else {
                            mainPullRefreshView[pos].setLoad();
                            vm.getSpecial(pos, idArrayList.get(pos));
                        }
                    }

                    @Override
                    public void onLoadMore() {

                    }
                });
            }
            for (int i = 0; i < idArrayList.size(); i++) {
                if (idArrayList.get(i).equals("0")) {
                    mainPullRefreshView[0].setLoad();
                    vm.getIndex();
                } else {
                    mainPullRefreshView[i].setLoad();
                    vm.getSpecial(i, idArrayList.get(i));
                }
            }
        });

        vm.getIndexLiveData().observe(this, list -> {
            arrayList[0].clear();
            arrayList[0].addAll(list);
            if (arrayList[0].size() == 0) {
                mainPullRefreshView[0].setEmpty();
            } else {
                mainPullRefreshView[0].setComplete();
            }
            vm.getArticleList();
        });

        vm.getArticleListLiveData().observe(this, list -> {
            if (list.size() != 0 && arrayList[0].size() != 0) {
                SpecialBean specialBean = new SpecialBean();
                specialBean.setArticleList(list);
                arrayList[0].add(2, specialBean);
                mainPullRefreshView[0].setComplete();
            }
        });

        vm.getSpecialLiveData().observe(this, data -> {
            arrayList[data.getPos()].clear();
            arrayList[data.getPos()].addAll(data.getSpecialArrayList());
            if (arrayList[data.getPos()].size() == 0) {
                mainPullRefreshView[data.getPos()].setEmpty();
            } else {
                mainPullRefreshView[data.getPos()].setComplete();
            }
        });

        vm.getErrorLiveData().observe(this, bean -> {
            switch (bean.getCode()) {
                case 1:
                    DialogHelp.get().query(getActivity(), R.string.loadFailure, bean.getReason(), view -> vm.getSpecialList(), view -> vm.getSpecialList());
                    break;
                case 2:
                    if (arrayList[0] != null && arrayList[0].size() != 0) {
                        ToastHelp.get().show(bean.getReason());
                    } else {
                        mainPullRefreshView[0].setError(bean.getReason());
                    }
                    break;
                case 3:
                    ToastHelp.get().show(bean.getReason());
                    break;
                case 4:
                    String reason = bean.getReason();
                    int position = ConvertUtil.string2Int(reason.substring(0, reason.indexOf("|")));
                    if (arrayList[position] != null && arrayList[position].size() != 0) {
                        ToastHelp.get().show(bean.getReason());
                    } else {
                        mainPullRefreshView[position].setError(reason.substring(reason.indexOf("|") + 1));
                    }
                    break;
            }
        });

        LiveEventBus.get(Constant.DATA_CONTENT, String.class).observe(this, string -> searchEditText.setHint(string));

        LiveEventBus.get(Constant.DATA_MSG_COUNT, String.class).observe(this, string -> {
            messageDotTextView.setVisibility(string.equals("0") ? View.GONE : View.VISIBLE);
            messageDotTextView.setText(string);
        });

    }

    @Override
    public void onResume() {

        super.onResume();
        if (!App.get().isMemberLogin()) {
            messageDotTextView.setVisibility(View.GONE);
        }

    }

}
